package com.sx.zongzhi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sx.zongzhi.BaseActivity;
import com.sx.zongzhi.R;
import com.sx.zongzhi.adapter.HouseAdapter;
import com.sx.zongzhi.bean.FactHouseSearchBean;
import com.sx.zongzhi.bean.HouseBean;
import com.sx.zongzhi.bean.MsgEvent;
import com.sx.zongzhi.bean.OrganizingBean;
import com.sx.zongzhi.bean.UserBean;
import com.sx.zongzhi.bean.UserPermission;
import com.sx.zongzhi.presenter.FactHousePest;
import com.sx.zongzhi.utils.AppConstants;
import com.sx.zongzhi.utils.Global;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.IFactHouseView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import xiaofei.library.datastorage.DataStorageFactory;
import xiaofei.library.datastorage.IDataStorage;

/**
 * 实有房屋列表
 */
public class FactHouseActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, IFactHouseView {

    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_Total)
    TextView tvTotal;
    @BindView(R.id.imvAdd)
    ImageView imvAdd;

    private HouseAdapter houseAdapter;
    private List<HouseBean> houseList = new ArrayList<>();

    private int page = 1, rows = 10;
    private Boolean isRentalHouse = null;
    private String orgId = "",address = "", name = "", nowLiveAddress = "", houseUsesId = "",
     houseAreaStart = "", houseAreaEnd = "";

    private Disposable disposable;
    private boolean isCurrentGrid = false;
    private UserPermission userPermission;

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_household);
        setTitleName(R.string.fact_house);
        ButterKnife.bind(this);
        setRightImage(R.mipmap.icon_nav_search);
        initViews();
        initRx();
    }

    private void initViews() {
        IDataStorage dataStorage= DataStorageFactory.getInstance(
                getApplicationContext(),
                DataStorageFactory.TYPE_DATABASE);
        UserBean userBean = dataStorage.load(UserBean.class,getPackageName());
        orgId = userBean.getOrg().getId();
        imvAdd.setVisibility(View.GONE);
        if ("片组片格".equals(userBean.getOrg().getOrgLevel().getDisplayName())){
            isCurrentGrid = true;
        }else {
            setRightImage2(R.mipmap.icon_nav_position);
        }
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setColorSchemeResources(AppConstants.colors);
            swipeRefreshLayout.setOnRefreshListener(this);
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        houseAdapter = new HouseAdapter(this, R.layout.item_house_list, houseList);
        houseAdapter.setEmptyView(View.inflate(this, R.layout.load_error_view, null));
        recyclerView.setAdapter(houseAdapter);
        houseAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                page++;
                getData();
            }
        }, recyclerView);

        houseAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(FactHouseActivity.this, FactHouseDetailActivity.class)
                .putExtra("id",houseList.get(position).getId())
                .putExtra("userPermission",userPermission)
                        .putExtra("HouseType",0));
            }
        });
        onRefresh();
    }

    private void initRx() {
        disposable = MyRxBus.get().toObservable(MsgEvent.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MsgEvent>() {
                    @Override
                    public void accept(MsgEvent bean) throws Exception {
                        if (bean.getRequest().equals("FactHouseActivity")) {
                            if (bean.getType() == 0) {//选组织结构
                                OrganizingBean oBean = (OrganizingBean) bean.getMsg();
                                if (oBean != null) {
                                    orgId = oBean.getId();
                                    if (oBean.isGrid() && userPermission != null && userPermission.isAddActualHouse()){
                                        imvAdd.setVisibility(View.VISIBLE);
                                    }else {
                                        imvAdd.setVisibility(View.GONE);
                                    }
                                }
                                page = 1;
                                getData();
                            } else if (bean.getType() == 2) {//筛选
                                FactHouseSearchBean bean1 = (FactHouseSearchBean) bean.getMsg();
                                address = bean1.address;
                                name = bean1.name;
                                nowLiveAddress = bean1.nowLiveAddress;
                                houseUsesId = bean1.houseUsesId;
                                houseAreaStart = bean1.houseAreaStart;
                                houseAreaEnd = bean1.houseAreaEnd;
                                isRentalHouse = bean1.isRentalHouse;
                                page = 1;
                                getData();
                            }else if (bean.getType() != 2 && bean.getType() != 0) {
                                onRefresh();
                            }
                        }
                    }
                });
    }

    @OnClick({R.id.imv_Right, R.id.imv_Right2, R.id.imvAdd})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.imv_Right://搜索
                startActivity(new Intent(this, FactHouseSearchActivity.class).putExtra("isRental",false));
                break;
            case R.id.imv_Right2://位置
                startActivity(new Intent(this, OrganizingActivity.class).
                        putExtra(Global.ACTIVITY_FRAGMENT, "FactHouseActivity"));
                break;
            case R.id.imvAdd://添加
                startActivity(new Intent(this, AddFactHouseActivity.class).putExtra("orgId",orgId));
                break;
        }
    }

    @Override
    public void onRefresh() {
        swipeRefreshLayout.setRefreshing(false);
        page = 1;
        address = "";
        name = "";
        nowLiveAddress = "";
        houseUsesId = "";
        houseAreaStart = "";
        houseAreaEnd = "";
        isRentalHouse = null;
        getData();
    }

    private void getData() {
            new FactHousePest(this).getFactHouseList(this, page, rows,isRentalHouse,orgId,address,name,nowLiveAddress,
                    houseUsesId,houseAreaStart,houseAreaEnd);
    }

    @Override
    public void getFactHouseListSuccess(UserPermission userPermissions, List<HouseBean> mailBeanLists, int total) {
        if (userPermissions != null && userPermission == null){
            userPermission = userPermissions;
            if (isCurrentGrid && userPermission.isAddActualHouse()){
                imvAdd.setVisibility(View.VISIBLE);
            }
        }
        if (swipeRefreshLayout.isRefreshing()){
            swipeRefreshLayout.setRefreshing(false);
        }
        if (page == 1) {
            houseList.clear();
            houseAdapter.setNewData(houseList);
        }
        if (mailBeanLists != null && mailBeanLists.size() > 0) {
            houseList.addAll(mailBeanLists);
        }
        houseAdapter.notifyDataSetChanged();
        tvTotal.setText("共" + total + "条数据");
        if (houseList.size() == total){
            houseAdapter.loadMoreEnd();
        }else {
            houseAdapter.loadMoreComplete();
        }
    }

    @Override
    public void showError(String message) {
        if (swipeRefreshLayout.isRefreshing()){
            swipeRefreshLayout.setRefreshing(false);
        }
        ToastUtils.showToast(FactHouseActivity.this, message);
    }

    @Override
    protected void onDestroy() {
        if (disposable != null){
            disposable.dispose();
        }
        houseList = null;
        super.onDestroy();
    }
}
